import { createWebHistory,createRouter } from 'vue-router'
const authUrls = ['/member/mydata','/pay','/order','/admin','/mycart','/member/discount','/member/order']
import { useUserStore } from '@/store/user';
import { usePermissStore } from '@/store/permiss';
import { ElMessage } from 'element-plus';
import { inject } from 'vue'

// 方式1：通过 inject 使用
const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path:'/:pathMatch(.*)*',
            component:()=>import ('@/views/errorPage/errorPage.vue'),
        },
        {
            path:'/login',
            name:'login',
            component:()=>import ('@/views/LoginPage/LoginPage.vue'),
        },
        {
            path:'/',
            redirect:'/sy',
            name:'home',
            component:()=>import ('@/views/layout/layoutPage.vue'),
            children:[
                {
                    path:'/sy',
                    name:'sy',
                    component:()=>import ('@/views/homePage/homePage.vue'),
                },
                {
                    path:'/food',
                    name:'food',
                    redirect:'/food/all',
                    component:()=>import ('@/views/foodPage/foodPage.vue'),
                    children:[
                        {
                            path:'/food/:message',
                            component:()=>import ('@/views/foodPage/components/PageSubject.vue'),
                        },
                    ]
                },
                {
                    path:'/member',
                    name:'member',
                    component:()=>import ('@/views/memberPage/memberPage.vue'),
                    redirect:'/member/mydata',
                    children:[
                        {
                            path:'/member/mydata',
                            name:'mydata',
                            component:()=>import ('@/views/memberPage/mydataPage/mydataPage.vue'),
                        },
                        {
                            path:'/member/discount',
                            name:'discount',
                            component:()=>import ('@/views/memberPage/discountPage/discountPage.vue'),
                        },
                        {
                            path:'/member/manage',
                            name:'manage',
                            component:()=>import ('@/views/memberPage/ManagePage/ManagePage.vue'),
                        },
                    ]
                },
                {
                    path:'/detail/:id',
                    name:'detail',
                    component:()=>import ('@/views/foodDetail/foodDetail.vue')
                },
                {
                    path:'/mycart',
                    name:'mycart',
                    component:()=>import ('@/views/cartPage/cartPage.vue')
                },
                {
                    path:'/pay',
                    name:'pay',
                    component:()=>import ('@/views/payPage/payPage.vue'),
                },
                {
                    path:'/search/:searchData',
                    name:'search',
                    component:()=>import ('@/views/searchPage/searchPage.vue')
                },
                {
                    path:'/order',
                    name:'order',
                    component:()=>import ('@/views/orderPage/orderPage.vue')
                },
            ]
        },
       
    ]
})

const permissList = [
    {
        path:'/admin',
        name:'admin',
        component:()=>import ('@/views/adminPage/adminPage.vue'),
        meta:{
            permiss: 3
        }
    },
]
let flag = true
router.beforeEach(async (to,from,next)=>{
     // 确保先清除之前可能存在的性能标记
  window.performance.clearMarks()
  window.performance.clearMeasures()
  
  // 记录路由跳转开始时间
  window.performance.mark('routeStart')
    const userStore = useUserStore();
    const store = usePermissStore();
    if(flag && userStore.userData.UID){
        permissList.forEach((item)=>{
            if(store.roleList.includes(item.meta.permiss)){
                router.addRoute('home',item)
            }
        })
        flag = false
        return next(to.path)
    }
    if(to.path !== '/login' && !userStore.token){
        next('/login')
    }
    if(!authUrls.includes(to.path)){
        next()
    }
   else{
    if(!userStore.token) {
        ElMessage({ type: 'error', message:'请您先登录认证！'})
        next('/login')
    }
    else{
        if(to.path === '/pay' && from.path !== '/mycart') router.back(-1)
        else {
            next()
        }
    }
   }
})

router.afterEach((to,from) => {
    const monitor = inject('monitor')
    // 记录路由跳转结束时间
    window.performance.mark('routeEnd')
    
    // 计算路由跳转耗时
    window.performance.measure('routeChange', 'routeStart', 'routeEnd')
    
    const measure = window.performance.getEntriesByName('routeChange')[0]
    // 获取 Vue 实例上的监控对象
    // 上报路由性能数据
    monitor.reporter.send('performance', {
      type: 'route',
      name: `${from.path} -> ${to.path}`,
      duration: measure.duration,
      timestamp: Date.now()
    })
    
    // 清除性能标记
    window.performance.clearMarks()
    window.performance.clearMeasures()
  })

export default router